package xyz.kongbai121.common.utils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 文件下载工具类
 *
 * @author kongbai121
 * @date 2021/11/24/15:01
 */
public class FileDownloadUtils {

    /**
     * 服务器文件下载
     *
     * @param response response
     * @param file     文件
     */
    public static void exportFile(HttpServletResponse response, File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        response.setContentType("application/x-download");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
        ServletOutputStream out = response.getOutputStream();
        int b = 0;
        byte[] buffer = new byte[512];
        while (b != -1) {
            b = inputStream.read(buffer);
            //4.写到输出流(out)中
            out.write(buffer, 0, b);
        }
        inputStream.close();
        out.close();
        out.flush();
        inputStream.close();
    }
}
